<?php
class NewsController extends NewsAppController {

	var $name = 'News';
	var $helpers = array('Html', 'Form');
	var $components =  array('Images.Attachment','RequestHandler');
	var $uses = array('News.News','Images.Image');
		
	function beforeFilter(){
		parent::beforeFilter();
		$this->layout = 'administrador';
		
	}
	function index() {
		$this->paginate['order'] = 'News.id DESC';
		$this->News->recursive = 0;
		$this->set('news', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->flash(__('Invalid News', true), array('action'=>'index'));
		}
		$this->set('news', $this->News->read(null, $id));
	}

	function add() {
			if (!empty($this->data)){
				$this->News->create();
				
				if ($this->News->save($this->data)) {
					$file_path = $this->Attachment->upload($this->data['Image']['Attachment'],'News');
					if($images = $this->Image->save_image('News',$this->News->getLastInsertId(),$file_path)){
						$this->Session->setFlash(__('Noticia guardada', true));
					}else{
						$this->Session->setFlash(__('Error al guardar la imagen. Intente nuevamente', true));
					}
					$this->redirect(array('action'=>'index'));
				} else {
					$this->Session->setFlash(__('Erro al guardar, intente nuevamente.', true));
				}
			}
	}
	
	

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->flash(__('Invalid News', true), array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->News->save($this->data)) {
				$this->flash(__('The News has been saved.', true), array('action'=>'index'));
			} else {
			}
		}
		if (empty($this->data)) {
			$this->data = $this->News->read(null, $id);
			
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->flash(__('Invalid News', true), array('action'=>'index'));
		}
		$new = $this->News->findById($id);
		if ($this->News->del($id)){
			$this->Image->delete_img('News',$id);
			$this->Attachment->delete_files($new['Image']['files'],'News');
			$this->redirect($this->referer());
		}
	}

}
?>